import { Module } from "vuex"
import { RootState } from "../index"
import http from "@/utils/http"
import { FlatToTree } from "@/utils/format"
import type { FileItemType } from "@/views/home/components/LeftBar/components/FileTree/type"

const state = {
  data: [] as Array<FileItemType>,
  flag: true,
  treeExpandedArr: [] as Array<string>,
}

export type FileTreeState = typeof state

export const store: Module<FileTreeState, RootState> = {
  namespaced: true,
  state,
  mutations: {
    changeTreeExpandedArr(
      state: FileTreeState,
      TreeExpandedArr: FileTreeState["treeExpandedArr"]
    ) {
      state.treeExpandedArr = TreeExpandedArr
    },
    switchFileTree(state: FileTreeState, flag: boolean) {
      state.flag = flag
    },
  },
  actions: {
    async getFile({ state }) {
      const res = await http.get<Array<FileItemType>>("/file/getFile")
      if (res.code === 1) {
        state.data = FlatToTree(res.data as Array<FileItemType>, "parentId")
      }
    },
  },
}
